package com.app.couponsharelife.ui.main.shop.jdfragment

import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.adapter.GoodsSearchAdapter
import com.app.couponsharelife.utils.DataUtils
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_jdgoodslist.*

/**
 *Created by xct on 2019/1/16
 *Description:
 */
class JDGoodsListFrag:LazyFragment() {
    private var homeClassBean: HomeClassBean?=null
    private var animationDrawable:AnimationDrawable?=null
    private var pageIndex=1
    private var keyword=""
    private var adapter: GoodsSearchAdapter?=null
    private var goodsList= arrayListOf<TaobaoGoodBean>()
    companion object {
        fun newInstance(homeClassBean: HomeClassBean): JDGoodsListFrag {
            val fragment = JDGoodsListFrag()
            val bundle= Bundle()
            bundle.putParcelable("Data",homeClassBean)
            fragment.arguments =bundle
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_jdgoodslist

    override fun initViews() {
        homeClassBean=arguments!!.getParcelable("Data")
        setRefresh()
        if (homeClassBean!=null){
            keyword=homeClassBean!!.name
            adapter=GoodsSearchAdapter(activity!!,goodsList,"JD")
            jdgoodslist_rv.layoutManager= GridLayoutManager(activity!!,2)
            jdgoodslist_rv.adapter=adapter
        }
    }

    override fun lazyLoad() {
        getGoodsList(false)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        jdgoodslist_smart.setOnMultiPurposeListener(object : OnMultiPurposeListener {
            override fun onFooterMoving(footer: RefreshFooter?, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderStartAnimator(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                //animationDrawable!!.start()
            }

            override fun onFooterReleased(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {

            }

            override fun onHeaderMoving(header: RefreshHeader?, isDragging: Boolean, percent: Float, offset: Int, headerHeight: Int, maxDragHeight: Int) {
                setAnima(percent)
            }

            override fun onFooterFinish(footer: RefreshFooter?, success: Boolean) {

            }

            override fun onFooterStartAnimator(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderReleased(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                animationDrawable!!.start()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getGoodsList(false)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex=1
                getGoodsList(true)
            }

            override fun onHeaderFinish(header: RefreshHeader?, success: Boolean) {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable!!.stop()
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }

    private fun getGoodsList(isRefresh:Boolean){
        if (!isRefresh&&pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map=HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["keyword"]=keyword
        RetrofitWorker.retrofitWorker.getJDGoodsList(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().jdData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<JDGoodsListBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<JDGoodsListBean>) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (it.data!=null&&it.data!!.recordss.isNotEmpty()){
                            if (pageIndex==1){
                                goodsList.clear()
                                if (isRefresh){
                                    jdgoodslist_llerror.visibility= View.GONE
                                    jdgoodslist_rv.visibility= View.VISIBLE
                                    jdgoodslist_smart.finishRefresh()
                                }
                            }else{
                                jdgoodslist_smart.finishLoadMore()
                            }
                            goodsList.addAll(it.data!!.recordss)
                            if (it.data!!.recordss.size<10){
                                jdgoodslist_smart.finishLoadMoreWithNoMoreData()
                            }
                            pageIndex++
                            adapter!!.notifyDataSetChanged()
                        }else{
                            if (isRefresh){
                                jdgoodslist_smart.finishRefresh()
                            }
                            if (pageIndex==1&&goodsList.size==0){
                                jdgoodslist_smart.finishLoadMoreWithNoMoreData()
                                jdgoodslist_llerror.visibility= View.VISIBLE
                                jdgoodslist_rv.visibility= View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            jdgoodslist_smart.finishRefresh()
                        }
                        if (pageIndex>1){
                            jdgoodslist_smart.finishLoadMore()
                        }
                        if (pageIndex==1){
                            jdgoodslist_smart.finishLoadMoreWithNoMoreData()
                            jdgoodslist_llerror.visibility= View.VISIBLE
                            jdgoodslist_rv.visibility= View.GONE
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                            //Log.e("eeee","----->"+e.toString())
                        }
                    }

                })
    }
}